<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .input-group {
            margin-top: 5px;
        }
    </style>
</head>

<body>
    <form class="addForm" onsubmit="return false">
        <div class="input-group">
            <label>姓名: <input type="text" name="name"></label>
        </div>
        <div class="input-group">
            <label>班级: <input type="text" name="class"></label>
        </div>
        <div class="input-group">
            <label>语文: <input type="text" name="ch"></label>
        </div>
        <div class="input-group">
            <label>数学: <input type="text" name="mh"></label>
        </div>
        <div class="input-group">
            <label>英语: <input type="text" name="eh"></label>
        </div>
        <div class="input-group">
            <input type="submit" class="subBtn" value="提交">
            <input type="reset" value="重置">
        </div>
    </form>
</body>
<script>

    // var nameInp = document.getElementsByName("name")[0];
    // var classInp = document.getElementsByName("class")[0];
    // var chInp = document.getElementsByName("ch")[0];
    // var mhInp = document.getElementsByName("mh")[0];
    // var ehInp = document.getElementsByName("eh")[0];

    var form = document.getElementsByClassName("addForm")[0];
    var subBtn = document.getElementsByClassName("subBtn")[0];

    // form元素 可以对应 name属性的属性值 来快捷获取表单内的表单控件
    // console.log(form);
    // console.log(form.name);
    // console.log(form.class);
    // console.log(form.ch);
    // console.log(form.mh);
    // console.log(form.eh);


    subBtn.onclick = function () {
        var name = form.name.value;
        var cls = form.class.value;
        var ch = form.ch.value;
        var mh = form.mh.value;
        var eh = form.eh.value;

        if (name && cls && ch && mh && eh) {

            var xhr = new XMLHttpRequest();

            xhr.open("post", "../php/addGrade.php", true);

            // FormData
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(`name=${name}&class=${cls}&ch=${ch}&mh=${mh}&eh=${eh}`);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var result = xhr.responseText;

                    result = JSON.parse(result);
                    console.log(result);
                    var { status, message } = result;
                    if (status) {
                        location.href = "index.html";
                    } else {
                        alert(message);
                    }


                }
            }



        }

    }



</script>

</html>